﻿@page "/"
@page "/{TimerEnable}"
@using Compass.Wasm.Shared.Extensions

@inject IMainPlanService MainPlanService
@inject IIssueService IssueService
<PageTitle>主页</PageTitle>

<!--sticky固定位置，top: 3.5rem-->
<div style="position: sticky; top: 3.5rem; z-index: 1;background-color:White">
    <div class="row position-relative">
        <div class="col input-group mb-2">
            <span class="input-group-text">搜索</span>
            <input class="form-control" placeholder="Search"
                   @bind-value="@_search" @oninput="@Search" />
        </div>
        <div class="col form-check ms-3 mt-2" style="max-width: 70px">
            <input class="form-check-input"
                   type="checkbox"
                   value="@_annual"
                   @onchange="OnAnnualChange">
            <label class="form-check-label">
                全年
            </label>
        </div>
        <div class="col input-group mb-2" style="max-width: 230px">
            <span class="input-group-text">月份</span>
            <input class="form-control"
                   type="month"
                   value="@(_selectedMonth.ToString("yyyy-MM"))"
                   format="" @onchange="OnMonthChange" />
        </div>
        <div class="col form-check ms-3 mt-2" style="max-width: 100px">
            <input class="form-check-input" type="checkbox" value="@_fromMonth"
                   checked="checked" @onchange="OnFromMonthChange">
            <label class="form-check-label">
                本月往后
            </label>
        </div>
        <div class="col mt-2">
            <div class="form-check ms-3">
                <input class="form-check-input" type="checkbox" value="@TimerEnable"
                       @onchange="OnTimerEnableChange">
                <label class="form-check-label ms-2">Loop</label>
            </div>
        </div>
    </div>
</div>

<table class="table table-hover table-striped" style="table-layout: fixed; word-break: break-all;">
    <!--sticky固定位置，top: 6rem-->
    <thead style="position: sticky; top: 6rem; z-index: 1; background-color: White">
        <tr>
            <th style="width: 60px; text-align: center; color: dodgerblue">状态</th>
            <th style="width: 50px; color: dodgerblue">分批</th>
            <th style="width: 120px; color: dodgerblue">项目编号</th>
            <th style="width: 25%; color: dodgerblue">项目名称</th>
            <th style="color: purple">计划发图</th>
            <th style="color: darkgreen">发图时间</th>
            <th style="color: purple">计划完工</th>
            <th style="color: darkgreen">入库时间</th>
            <th style="color: darkgreen">发货时间</th>
            <th style="color: blue">装箱信息</th>
            <th style="color: blue">
                <a href="issues">总结问题</a>
            </th>
            <th style="color: blue">
                <a href="lessons">总结经验</a>
            </th>
        </tr>
    </thead>
    <tbody>
        @if (_filterMainPlanDtos.Count == 0)
        {
            <p>...</p>
        }
        else
        {
            @foreach (var plan in _filterMainPlanDtos)
            {
                <tr class="@(plan.AllIssueClosed ? "" : "table-danger")">
                    <td style="text-align: center">
                        <CompMainPlanStatus Status="@plan.Status"></CompMainPlanStatus>
                    </td>
                    <td>
                        <CompBatch Batch="plan.Batch" />
                    </td>
                    <td>
                        @if (plan.ProjectId != null)
                        {
                            <a href="./drawings/@plan.ProjectId">@plan.Number</a>
                        }
                        else
                        {
                            <a href="mainplan/bind/@plan.Id">绑定项目</a>
                        }
                    </td>
                    <td style="text-overflow: ellipsis; overflow: hidden; white-space: nowrap">@plan.Name</td>

                    <td style="font-weight: bold; @(plan.DrwReleaseTarget.Date < DateTime.Today.Date && plan.DrwReleaseTime == null ? "color:red" : plan.DrwReleaseTarget.Date < DateTime.Today.Date ? "color:green" : "")">
                        @plan.DrwReleaseTarget.ToString("MM/dd")
                    </td>
                    <td style="@(plan.DrwReleaseTime != null && plan.DrwReleaseTime.Value.Date>plan.DrwReleaseTarget.Date? "color:orange":"")">
                        <AuthorizeView Roles="admin">
                            <Authorized>
                                <!--todo:使用弹窗解决这个问题-->
                                <a href="mainplan/update/drwreleasetime/@plan.Id">
                                    <span class="oi oi-cog"></span>
                                </a>
                            </Authorized>
                        </AuthorizeView>
                        @(plan.DrwReleaseTime != null ?
                            plan.DrwReleaseTime.Value.ToString("MM/dd") : "")
                    </td>
                    <td style="font-weight: bold; @(plan.FinishTime.Date < DateTime.Today.Date && plan.Status < MainPlanStatus_e.入库 ? "color:red" : plan.FinishTime.Date < DateTime.Today.Date ? "color:green" : "")">
                        @plan.FinishTime.ToString("MM/dd")
                    </td>
                    <!--入库日期可以比完工日期晚一天，因此plan.FinishTime.Date.AddDays(1)-->
                    <td style="@(plan.WarehousingTime != null && plan.WarehousingTime.Value.Date>plan.FinishTime.Date.AddDays(1) ? "color:orange":"")">
                        @(plan.WarehousingTime != null ?
                            plan.WarehousingTime.Value.ToString("MM/dd") : "")
                    </td>
                    <td>
                        @(plan.ShippingTime != null ?
                            plan.ShippingTime.Value.ToString("MM/dd") : "")
                    </td>
                    <td>
                        @if (plan.HavePackingList)
                        {
                            <a href="pallets/mainplan/@plan.Id">装箱信息</a>
                        }
                    </td>
                    <td>
                        @if (plan.AllIssueClosed)
                        {
                            <a href="issue/add/@plan.Id">报告异常</a>
                        }
                        else
                        {
                            <a href="issues/mainplan/@plan.Id">
                                <span>@plan.IssueTitles</span>
                                <img class="ms-1 me-2" style="width: 23px" src="andon_red.gif" />
                            </a>
                        }
                    </td>
                    <td>
                        @if (plan.Status == MainPlanStatus_e.发货 && plan.AllIssueClosed)
                        {
                            <a href="lessons/mainplan/@plan.Id">结束项目</a>
                        }
                        else if (plan.Status == MainPlanStatus_e.结束)
                        {
                            <a href="lessons/mainplan/@plan.Id">
                                @(plan.ClosedTime != null ?
                                    plan.ClosedTime.Value.ToString("MM/dd") : "") 结束
                            </a>
                        }
                        else
                        {
                            <a href="lesson/add/@plan.Id">添加经验</a>
                        }
                    </td>
                </tr>
            }
        }
    </tbody>
</table>


@code {

    private string _search = string.Empty;
    private bool _annual;
    private bool _fromMonth = true;
    private DateTime _selectedMonth = DateTime.Today;
    private int _year;
    private int _month;

    private List<MainPlanDto> _mainPlanDtos = new();
    private List<MainPlanDto> _filterMainPlanDtos = new();

    [Parameter]
    public string TimerEnable { get; set; }
    private bool _timerEnable;
    System.Timers.Timer _timer;//定时触发

    protected override async Task OnParametersSetAsync()
    {
        _year= _selectedMonth.Year;
        _month= _selectedMonth.Month;
        //初始化定时器
        _timer = new System.Timers.Timer(20000);//间隔20s
        _timer.Elapsed += (sender, eventArgs) => OnTimerCallback();
        //将TimerEnable
        _timerEnable = TimerEnable.ToBool();
        if (_timerEnable)
        {
            _timer.Start();
        }
        else
        {
            _timer.Stop();
        }

        //过滤条件变化
        await GetData();
        Search(new ChangeEventArgs { Value = _search });
        StateHasChanged();
    }

    private async void OnAnnualChange(ChangeEventArgs e)
    {
        _annual =Convert.ToBoolean(e.Value);
        await GetData();
        Search(new ChangeEventArgs { Value = _search });
        StateHasChanged();
    }

    private async void OnFromMonthChange(ChangeEventArgs e)
    {
        _fromMonth =Convert.ToBoolean(e.Value);
        await GetData();
        Search(new ChangeEventArgs { Value = _search });
        StateHasChanged();
    }

    private async void OnMonthChange(ChangeEventArgs e)
    {
        _selectedMonth = Convert.ToDateTime(e.Value);
        _year = _selectedMonth.Year;
        _month= _selectedMonth.Month;
        await GetData();
        Search(new ChangeEventArgs { Value = _search });
        StateHasChanged();
    }

    private async Task GetData()
    {
        _mainPlanDtos.Clear();
        _mainPlanDtos.AddRange(await MainPlanService.GetBlazorMainPlansAsync(_year, _month, _annual, _fromMonth, true, false));
        //异步方法需要主动告知前台状态已经发生改变
        StateHasChanged();
    }

    private void Search(ChangeEventArgs e)
    {
        //将搜索放在外面做（4.没搜索||5.搜索项目号||6.搜索项目名称）
        _search=e.Value!.ToString()!;
        _filterMainPlanDtos.Clear();
        _filterMainPlanDtos.AddRange(_mainPlanDtos.Where(
            x => string.IsNullOrEmpty(_search) ||
                 x.Number.ToLower().Contains(_search.ToLower()) ||
                 x.Name.ToLower().Contains(_search.ToLower())));

        StateHasChanged();
    }

    private void OnTimerEnableChange(ChangeEventArgs e)
    {
        _timerEnable =Convert.ToBoolean(e.Value);
        TimerEnable = _timerEnable.ToString();
        if (_timerEnable)
        {
            _timer.Start();
        }
        else
        {
            _timer.Stop();
        }
    }
    //计时器执行的操作
    private int _page = 0;
    public void OnTimerCallback()
    {
        _ = InvokeAsync(() =>
        {
            //循环展示时，每次只显示10个项目
            _page++;
            if (_page > Math.Floor(_mainPlanDtos.Count/10d)) _page = 0;
            _filterMainPlanDtos.Clear();
            _filterMainPlanDtos.AddRange(_mainPlanDtos.Skip(10*_page).Take(10));
            StateHasChanged();
        });
    }
}